<!DOCTYPE HTML>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <title>生成二维码</title>
  <style type="text/css">
    body {
      text-align: center;
    }

    div {
      padding: 10px;
      border: 1px rgb(188, 188, 188) solid;
      width: 256px;
      height: 256px;
      margin: 50px auto 20px;
    }

    #text {
      font-size: 16px;
      padding: 4px;
      width: 256px;
    }
  </style>
</head>

<body>
  <div id="qrcode"></div>
  <p>
    <input type="text" id="text" />
  </p>
  <p>
    <input type="button" value="生成二维码" id="button" />
  </p>
  <script src="//cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script>
  <script src="//cdn.bootcss.com/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>
  <script type="text/javascript">
    function unicode2uft8(str) {
      var out = "",
        len = str.length,
        i,
        c
      for (i = 0; i < len; i++) {
        c = str.charCodeAt(i)
        if (c <= 0x007f) {
          out += str.charAt(i)
        } else if (c <= 0x07ff) {
          out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F))
          out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
        } else {
          out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F))
          out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F))
          out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
        }
      }
      return out
    }

    function qrcode() {
      var text = $("#text").val().trim() || location.href
      $('#qrcode').empty().qrcode({
        render: 'canvas',
        text: unicode2uft8(text),
        height: 256,
        width: 256,
        typeNumber: -1, //计算模式
        // correctLevel: QRErrorCorrectLevel.M, //纠错等级
        background: "#ffffff", //背景颜色
        foreground: "#000000"
      })
    }

    $("#button").bind("click", qrcode);
    $("#text").on('keydown', function (e) {
      if (e.keyCode === 13) {
        qrcode()
      }
    })

    qrcode()
  </script>
</body>

</html>